package com.common.result;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.Accessors;

/**
 * 响应信息主体
 */
@Builder
@ToString
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
@ApiModel(value = "响应信息主体")
public class R<T> implements Serializable {

	public static final Integer SUCCESS = 0;
	public static final Integer FAIL = 1;
	public static final Integer ERROR = 2;
	private static final long serialVersionUID = 1L;
	@Getter
	@Setter
	@ApiModelProperty(value = "返回标记：成功标记=0，失败标记=1,错误标记=3")
	private int code;

	@Getter
	@Setter
	@ApiModelProperty(value = "返回信息")
	private String msg;


	@Getter
	@Setter
	@ApiModelProperty(value = "数据")
	private T data;

	public static <T> R<T> ok() {
		return restResult(null, SUCCESS, "success");
	}

	public static <T> R<T> ok(T data) {
		return restResult(data, SUCCESS, "success");
	}

	public static <T> R<T> ok(T data, String msg) {
		return restResult(data, SUCCESS, msg);
	}

	public static <T> R<T> error(T data, String msg) {
		return restResult(data, ERROR, msg);
	}

	public static <T> R<T> error(String msg) {
		return restResult(null, ERROR, msg);
	}

	public static <T> R<T> failed() {
		return restResult(null, FAIL, "fail");
	}

	public static <T> R<T> failed(String msg) {
		return restResult(null, FAIL, msg);
	}

	public static <T> R<T> failed(T data) {
		return restResult(data, FAIL, "fail");
	}

	public static <T> R<T> failed(T data, String msg) {
		return restResult(data, FAIL, msg);
	}

	private static <T> R<T> restResult(T data, int code, String msg) {
		R<T> apiResult = new R<>();
		apiResult.setCode(code);
		apiResult.setData(data);
		apiResult.setMsg(msg);
		return apiResult;
	}
}
